<%-- 
    Document   : addToCart
    Created on : Oct 8, 2012, 11:34:40 PM
    Author     : Nhan
--%>
<%@page import="com.Checker"%>
<%@page import="com.Cart"%>
<%@page import="com.Book"%>
<%@page import="java.util.ArrayList"%>

<%!
    ArrayList<Cart> selectedItems;

    public void handleAddToCart(HttpServletRequest request, ArrayList<Cart> selectedItems) {

        String id = request.getParameter("bookID");
        if(id != null) {
            if(selectedItems == null) {
                selectedItems = new ArrayList<Cart>();
            }
            Book targetBook = Checker.getBookInfo(id);

            int quantity = 1;
            int indexFound = isAdded(selectedItems, id);

            if(indexFound != -1) {
                //update so luong khi da add roi
                Cart item = selectedItems.get(indexFound);
                int curNumItem = item.getNumItem();
                item.setNumItem(curNumItem++);
                selectedItems.set(indexFound, item);
            } else {
                //them vao shopping cart khi chua dc add
                //int id, String title, String image, String author,
                //String type, int numItem, float price
                selectedItems.add(new Cart(Integer.valueOf(id),targetBook.getTitle(), targetBook.getImage()
                        , targetBook.getAuthor(), targetBook.getType(), quantity, targetBook.getPrice()));
            }

            HttpSession session = request.getSession();
            if(selectedItems != null) session.setAttribute("selectedItems", selectedItems);

        }

    }

    int isAdded(ArrayList<Cart> selectedItems, String id) {
        for(int i = 0 ; i < selectedItems.size() ; i++) {
            String bookID = selectedItems.get(i).getId() + "";
            if(bookID.equals(id)) {
                return i;
            }
        }
        return -1;
    }
%>